<template>
  <div class="video-course-app">
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :show-search="false"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
    />

    <!-- Main Content -->
    <div class="main-container">
      <!-- Sidebar -->
      <aside class="sidebar">
        <div class="sidebar-header">
          <h3>视频课程列表</h3>
          <div class="sidebar-actions">
            <button class="btn btn-primary btn-sm" @click="showAddCourseModal" title="创建新课程">
              <i class="fas fa-plus"></i>
            </button>
          </div>
        </div>
        
        <div class="course-list">
          <div 
            v-for="course in videoCourses" 
            :key="course?.id || index"
            class="course-item"
            :class="{ active: currentCourse && currentCourse.id === course?.id }"
            @click="selectCourse(course)"
          >
            <div class="course-info">
              <div class="course-name">{{ course?.name || '未命名课程' }}</div>
              <div class="course-chapters">{{ (course?.chapters ? course.chapters.length : 0) }} 视频</div>
            </div>
            <div class="course-actions">
              <button 
                class="action-btn" 
                @click.stop="editCourse(course)"
                title="编辑课程"
              >
                <i class="fas fa-edit"></i>
              </button>
              <button 
                class="action-btn" 
                @click.stop="deleteCourse(course)"
                title="删除课程"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
          
          <!-- 创建新课程按钮卡片 -->
          <div class="course-item add-course" @click="showAddCourseModal">
            <div class="add-course-content">
              <i class="fas fa-plus"></i>
              <span>创建新课程</span>
            </div>
          </div>
        </div>
      </aside>

      <!-- Content Area -->
      <main class="content">
        <div class="content-header">
          <nav class="breadcrumb">
            <router-link to="/" class="breadcrumb-item">首页</router-link>
            <span v-if="currentCourse" class="breadcrumb-item">{{ currentCourse?.name || '未命名课程' }}</span>
            <span v-if="currentChapter" class="breadcrumb-item">{{ currentChapter?.title || '未命名视频' }}</span>
          </nav>
        </div>

        <!-- Welcome Screen -->
        <div class="welcome-screen" v-if="!currentCourse">
          <div class="welcome-content">
            <i class="fas fa-video"></i>
            <h2>欢迎使用视频课程系统</h2>
            <p>开始创建您的第一个视频课程，分享知识内容</p>
            <button class="btn btn-primary" @click="showAddCourseModal">
              创建第一个视频课程
            </button>
          </div>
        </div>

        <!-- Chapter List View -->
        <div class="chapter-view" v-if="currentCourse && !currentChapter">
          <div class="chapter-header">
            <h2>{{ currentCourse?.name || '未命名课程' }}</h2>
            <button class="btn btn-primary" @click="showAddChapterModal">
              <i class="fas fa-plus"></i>
              新增视频
            </button>
          </div>
          
          <div class="chapter-grid">
            <div 
              v-for="(chapter, index) in (currentCourse?.chapters || [])" 
              :key="chapter?.id || index"
              class="chapter-card video-chapter-card"
              @click="editChapter(chapter)"
            >
              <div class="video-thumbnail">
                <div class="thumbnail-placeholder">
                  <i class="fas fa-play-circle"></i>
                </div>
                <div class="video-duration" v-if="chapter?.duration">
                  {{ formatDuration(chapter.duration) }}
                </div>
                <div class="video-number">{{ index + 1 }}</div>
              </div>
              <div class="chapter-content">
                <h3>{{ chapter?.title || '未命名视频' }}</h3>
                <div class="chapter-meta">
                  <span>{{ getContentPreview(chapter?.description) }}</span>
                </div>
              </div>
              <div class="chapter-actions">
                <button class="action-btn" @click.stop="deleteChapter(chapter)" title="删除">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
            
            <div class="chapter-card add-chapter" @click="showAddChapterModal">
              <div class="add-chapter-content">
                <i class="fas fa-plus"></i>
                <span>添加新视频</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Video Editor View -->
        <div class="video-editor-view" v-if="currentChapter">
          <div class="editor-header">
            <div class="editor-title">
              <input 
                type="text" 
                v-model="currentChapter.title"
                placeholder="输入视频标题..." 
                class="title-input"
                @blur="saveChapter"
              >
            </div>
            <div class="editor-actions">
              <button class="btn btn-ghost" @click="saveChapter">
                <i class="fas fa-save"></i>
                保存
              </button>
              <button class="btn btn-ghost" @click="backToChapters">
                <i class="fas fa-arrow-left"></i>
                返回
              </button>
            </div>
          </div>

          <div class="video-form">
            <div class="form-group">
              <label for="videoUrl">视频链接</label>
              <input 
                type="url" 
                id="videoUrl"
                v-model="currentChapter.videoUrl"
                placeholder="输入视频链接 (支持 YouTube, Bilibili 等)"
                class="form-input"
                @blur="saveChapter"
              >
            </div>
            
            <!-- 文件上传部分 -->
            <div class="form-group">
              <label>或上传视频文件</label>
              <div class="file-upload-area">
                <input 
                  type="file" 
                  ref="videoFileInput"
                  accept="video/*"
                  class="file-input"
                  @change="handleFileUpload"
                >
                <div class="file-upload-placeholder" @click="triggerFileInput">
                  <i class="fas fa-cloud-upload-alt"></i>
                  <span>点击选择视频文件或拖拽到此处</span>
                </div>
                <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
                  </div>
                  <span>{{ uploadProgress }}%</span>
                </div>
              </div>
            </div>
            
            <div class="form-group">
              <label for="videoDuration">视频时长 (分钟)</label>
              <input 
                type="number" 
                id="videoDuration"
                v-model="currentChapter.duration"
                placeholder="输入视频时长"
                class="form-input"
                @blur="saveChapter"
              >
            </div>
            
            <div class="form-group">
              <label for="videoDescription">视频描述</label>
              <textarea 
                id="videoDescription"
                v-model="currentChapter.description"
                placeholder="输入视频描述..."
                class="form-textarea"
                rows="8"
                @blur="saveChapter"
              ></textarea>
            </div>
            
            <div class="video-preview" v-show="currentChapter && currentChapter.videoUrl">
              <h4>视频预览</h4>
              <div class="video-container">
                <!-- 如果是上传的视频文件，使用原生video标签播放 -->
                <video 
                  v-if="isUploadedVideo(currentChapter.videoUrl)"
                  :src="getProxyVideoUrl(currentChapter.videoUrl)" 
                  controls
                  width="100%" 
                  height="100%"
                  class="native-video-player"
                >
                  您的浏览器不支持视频播放。
                </video>
                <!-- 如果是外部链接，使用iframe嵌入 -->
                <iframe 
                  v-else
                  :src="getEmbedUrl(currentChapter.videoUrl)"
                  frameborder="0"
                  allowfullscreen
                  class="video-iframe"
                ></iframe>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- Add Course Modal -->
    <div class="modal" v-if="showCourseModal" @click="handleModalOverlayClick">
      <div class="modal-content">
        <div class="modal-header">
          <h3>新建视频课程</h3>
          <button class="modal-close" @click="hideCourseModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="courseName">课程名称</label>
            <input 
              type="text" 
              id="courseName" 
              v-model="newCourse.name"
              placeholder="输入课程名称..."
            >
          </div>
          <div class="form-group">
            <label for="courseDescription">课程描述</label>
            <textarea 
              id="courseDescription" 
              v-model="newCourse.description"
              placeholder="输入课程描述..." 
              rows="4"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="courseIsPublic">是否公开</label>
            <select 
              id="courseIsPublic" 
              v-model="newCourse.isPublic"
              class="form-select"
            >
              <option :value="true">公开（所有人可见）</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-ghost" @click="hideCourseModal">取消</button>
          <button class="btn btn-primary" @click="createCourse">创建课程</button>
        </div>
      </div>
    </div>

    <!-- Edit Course Modal -->
    <div class="modal" v-if="showEditCourseModal" @click="handleModalOverlayClick">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑视频课程</h3>
          <button class="modal-close" @click="hideEditCourseModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="editCourseName">课程名称</label>
            <input 
              type="text" 
              id="editCourseName" 
              v-model="editingCourse.name"
              placeholder="输入课程名称..."
            >
          </div>
          <div class="form-group">
            <label for="editCourseDescription">课程描述</label>
            <textarea 
              id="editCourseDescription" 
              v-model="editingCourse.description"
              placeholder="输入课程描述..." 
              rows="4"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="editCourseIsPublic">是否公开</label>
            <select 
              id="editCourseIsPublic" 
              v-model="editingCourse.isPublic"
              class="form-select"
            >
              <option :value="true">公开（所有人可见）</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-ghost" @click="hideEditCourseModal">取消</button>
          <button class="btn btn-primary" @click="updateCourse">保存修改</button>
        </div>
      </div>
    </div>

    <!-- Add Chapter Modal -->
    <div class="modal" v-if="showChapterModal" @click="handleModalOverlayClick">
      <div class="modal-content">
        <div class="modal-header">
          <h3>新增视频</h3>
          <button class="modal-close" @click="hideChapterModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="chapterTitle">视频标题</label>
            <input 
              type="text" 
              id="chapterTitle" 
              v-model="newChapter.title"
              placeholder="输入视频标题..."
            >
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-ghost" @click="hideChapterModal">取消</button>
          <button class="btn btn-primary" @click="createChapter">创建视频</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import apiService from '@/services/api.js'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'

export default {
  name: 'VideoCoursePage',
  components: {
    AppHeader
  },
  data() {
    return {
      videoCourses: [],
      currentUser: null,
      currentCourse: null,
      currentChapter: null,
      showCourseModal: false,
      showEditCourseModal: false,
      showChapterModal: false,
      newCourse: {
        name: '',
        description: '',
        isPublic: false // 添加是否公开字段，默认为私有
      },
      editingCourse: {
        id: null,
        name: '',
        description: '',
        isPublic: false // 添加是否公开字段
      },
      newChapter: {
        title: ''
      },
      uploadProgress: 0, // 添加上传进度数据
      plyrPlayer: null // 添加Plyr播放器实例
    }
  },
  mounted() {
    this.checkAuthStatus()
    this.loadData()
    this.handleRouteQuery()
  },
  watch: {
    // 监听currentChapter变化
    currentChapter: {
      handler() {
        // 无需特殊处理，原生播放器会自动处理
      },
      deep: true
    }
  },
  methods: {
    async loadData() {
      if (!this.currentUser) {
        this.videoCourses = []
        return
      }
      
      try {
        const response = await apiService.getVideoCourses()
        this.videoCourses = response.courses || []
      } catch (error) {
        console.error('加载视频课程失败:', error)
        this.videoCourses = []
      }
    },
    checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      const savedToken = localStorage.getItem('auth_token')
      
      if (savedUser && savedToken) {
        this.currentUser = JSON.parse(savedUser)
      }
    },
    handleRouteQuery() {
      const courseId = this.$route.query.courseId
      if (courseId) {
        const course = this.videoCourses.find(c => c.id === courseId)
        if (course) {
          this.selectCourse(course)
        }
      }
    },
    selectCourse(course) {
      this.currentCourse = course
      this.currentChapter = null
    },
    editChapter(chapter) {
      this.currentChapter = chapter
    },
    backToChapters() {
      this.currentChapter = null
    },
    toggleSidebar() {
      // Toggle sidebar visibility
    },
    showAddCourseModal() {
      this.showCourseModal = true
      this.newCourse = { name: '', description: '', isPublic: true }
    },
    hideCourseModal() {
      this.showCourseModal = false
    },
    showAddChapterModal() {
      this.showChapterModal = true
      this.newChapter = { title: '' }
    },
    hideChapterModal() {
      this.showChapterModal = false
    },
    async createCourse() {
      if (!this.newCourse.name.trim()) {
        await this.$alert('请输入课程名称', {
          title: '输入错误',
          variant: 'warning'
        })
        return
      }
      
      try {
        const courseData = {
          name: this.newCourse.name,
          description: this.newCourse.description,
          isPublic: this.newCourse.isPublic // 添加是否公开字段
        }
        
        const response = await apiService.createVideoCourse(courseData)
        const createdCourse = response // 修复：直接使用response而不是response.data
        
        this.videoCourses.push(createdCourse)
        this.hideCourseModal()
        
        await this.$toast('视频课程创建成功！', {
          title: '创建成功',
          variant: 'success'
        })
      } catch (error) {
        console.error('创建视频课程失败:', error)
        await this.$toast('创建视频课程失败: ' + (error.message || '未知错误'), {
          title: '创建失败',
          variant: 'error'
        })
      }
    },
    async createChapter() {
      if (!this.newChapter.title.trim()) {
        await this.$alert('请输入视频标题', {
          title: '输入错误',
          variant: 'warning'
        })
        return
      }
      
      try {
        const chapterData = {
          title: this.newChapter.title
        }
        
        const createdChapter = await apiService.addVideoChapter(this.currentCourse.id, chapterData)
        
        if (!this.currentCourse.chapters) {
          this.currentCourse.chapters = []
        }
        
        this.currentCourse.chapters.push(createdChapter)
        
        this.hideChapterModal()
        this.editChapter(createdChapter)
        
        // 显示成功提示
        this.$toast('视频创建成功', {
          title: '创建成功',
          variant: 'success'
        })
      } catch (error) {
        console.error('创建章节失败:', error)
        await this.$alert(error.message || '创建章节失败', {
          title: '创建失败',
          variant: 'error'
        })
      }
    },
    async deleteChapter(chapter) {
      const confirmed = await this.$confirm(
        `确定要删除视频"${chapter.title}"吗？`,
        {
          title: '删除视频',
          variant: 'error',
          confirmText: '删除'
        }
      )
          
      if (confirmed) {
        try {
          await apiService.deleteVideoChapter(this.currentCourse.id, chapter.id)
          
          const index = this.currentCourse.chapters.findIndex(c => c.id === chapter.id)
          if (index > -1) {
            this.currentCourse.chapters.splice(index, 1)
          }
          
          // 显示删除成功的Toast提示
          this.$toast(`视频"${chapter.title}"已删除`, {
            title: '删除成功',
            variant: 'success'
          })
        } catch (error) {
          console.error('删除章节失败:', error)
          this.$toast(error.message || '删除失败', {
            title: '删除失败',
            variant: 'error'
          })
        }
      }
    },
    async saveChapter() {
      if (this.currentChapter) {
        try {
          const chapterData = {
            title: this.currentChapter.title,
            videoUrl: this.currentChapter.videoUrl,
            duration: Number(this.currentChapter.duration) || 0,
            description: this.currentChapter.description
          }
          
          const updatedChapter = await apiService.updateVideoChapter(
            this.currentCourse.id, 
            this.currentChapter.id, 
            chapterData
          )
          
          // 更新本地数据
          const index = this.currentCourse.chapters.findIndex(c => c.id === this.currentChapter.id)
          if (index > -1) {
            this.currentCourse.chapters[index] = updatedChapter
          }
          
          this.currentChapter.lastModified = new Date().toISOString()
          
          // 显示保存成功的Toast提示
          this.$toast('视频保存成功', {
            title: '保存成功',
            variant: 'success'
          })
        } catch (error) {
          console.error('保存章节失败:', error)
          this.$toast(error.message || '保存章节失败', {
            title: '保存失败',
            variant: 'error'
          })
        }
      }
    },

    editCourse(course) {
      this.showEditCourseModal = true
      this.editingCourse = {
        id: course.id,
        name: course.name,
        description: course.description,
        isPublic: course.isPublic !== undefined ? course.isPublic : false // 初始化是否公开字段
      }
    },
    hideEditCourseModal() {
      this.showEditCourseModal = false
      this.editingCourse = {
        id: null,
        name: '',
        description: ''
      }
    },
    async updateCourse() {
      if (!this.editingCourse.name.trim()) {
        await this.$alert('请输入课程名称', {
          title: '输入错误',
          variant: 'warning'
        })
        return
      }
      
      try {
        const courseData = {
          name: this.editingCourse.name,
          description: this.editingCourse.description,
          isPublic: this.editingCourse.isPublic // 添加是否公开字段
        }
        
        const response = await apiService.updateVideoCourse(this.editingCourse.id, courseData)
        const updatedCourse = response // 修复：直接使用response而不是response.data
        
        const index = this.videoCourses.findIndex(c => c.id === this.editingCourse.id)
        if (index !== -1) {
          // 修复：在 Vue 3 中不需要使用 $set，直接替换数组元素即可
          this.videoCourses[index] = updatedCourse
        }
        
        if (this.currentCourse && this.currentCourse.id === this.editingCourse.id) {
          this.currentCourse = updatedCourse
        }
        
        this.hideEditCourseModal()
        
        await this.$toast('视频课程更新成功！', {
          title: '更新成功',
          variant: 'success'
        })
      } catch (error) {
        console.error('更新视频课程失败:', error)
        await this.$toast('更新视频课程失败: ' + (error.message || '未知错误'), {
          title: '更新失败',
          variant: 'error'
        })
      }
    },
    async deleteCourse(course) {
      const confirmed = await this.$confirm(
        `确定要删除视频课程“${course.name}”吗？此操作不可恢复。`,
        {
          title: '删除视频课程',
          variant: 'error',
          confirmText: '删除'
        }
      )
      
      if (confirmed) {
        try {
          await apiService.deleteVideoCourse(course.id)
          
          const index = this.videoCourses.findIndex(c => c.id === course.id)
          if (index > -1) {
            this.videoCourses.splice(index, 1)
          }
          
          // 如果删除的是当前正在编辑的课程，则清空当前状态
          if (this.currentCourse && this.currentCourse.id === course.id) {
            this.currentCourse = null
            this.currentChapter = null
          }
          
          // 显示删除成功的Toast提示
          this.$toast(`视频课程“${course.name}”已删除`, {
            title: '删除成功',
            variant: 'success'
          })
        } catch (error) {
          console.error('删除课程失败:', error)
          this.$toast(error.message || '删除课程失败', {
            title: '删除失败',
            variant: 'error'
          })
        }
      }
    },
    formatDuration(minutes) {
      if (!minutes) return '0:00'
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return hours > 0 ? `${hours}:${mins.toString().padStart(2, '0')}` : `${mins}:00`
    },
    getContentPreview(content) {
      if (!content) return '暂无描述'
      return content.length > 50 ? content.substring(0, 50) + '...' : content
    },
    getEmbedUrl(url) {
      if (!url) return ''
      
      // YouTube
      if (url.includes('youtube.com/watch?v=')) {
        const videoId = url.split('v=')[1].split('&')[0]
        return `https://www.youtube.com/embed/${videoId}`
      }
      
      // YouTube short URL
      if (url.includes('youtu.be/')) {
        const videoId = url.split('youtu.be/')[1].split('?')[0]
        return `https://www.youtube.com/embed/${videoId}`
      }
      
      // Bilibili
      if (url.includes('bilibili.com')) {
        // Extract BV number or av number
        const bvMatch = url.match(/BV[\w\d]+/)
        if (bvMatch) {
          return `https://player.bilibili.com/player.html?bvid=${bvMatch[0]}`
        }
      }
      
      // 腾讯视频
      if (url.includes('v.qq.com')) {
        const vidMatch = url.match(/[?&]vid=([\w\d]+)/) || url.match(/\/([\w\d]+)\.html/);
        if (vidMatch && vidMatch[1]) {
          return `https://v.qq.com/txp/iframe/player.html?vid=${vidMatch[1]}`;
        }
      }
      
      // 爱奇艺
      if (url.includes('iqiyi.com')) {
        const vidMatch = url.match(/\/([\w\d]+)\.html/);
        if (vidMatch && vidMatch[1]) {
          // 注意：爱奇艺的iframe嵌入可能需要特殊处理
          return `https://www.iqiyi.com/common/qplay.html?vid=${vidMatch[1]}`;
        }
      }
      
      // 优酷
      if (url.includes('youku.com')) {
        const vidMatch = url.match(/id_([\w\d=]+)/) || url.match(/[?&]vid=([\w\d]+)/);
        if (vidMatch && vidMatch[1]) {
          return `https://player.youku.com/embed/${vidMatch[1]}`;
        }
      }
      
      // 西瓜视频
      if (url.includes('ixigua.com')) {
        const vidMatch = url.match(/video\/([\w\d]+)/);
        if (vidMatch && vidMatch[1]) {
          return `https://www.ixigua.com/iframe/${vidMatch[1]}`;
        }
      }
      
      // For other URLs, return as is (assuming it's already an embed URL)
      return url
    },
    
    // 判断是否为上传的视频文件
    isUploadedVideo(url) {
      // 上传的视频文件URL包含/uploads/videos/路径
      return url && url.includes('/uploads/videos/');
    },
    
    // 获取视频文件的代理URL
    getProxyVideoUrl(url) {
      // 如果是上传的视频文件，使用代理路径
      if (this.isUploadedVideo(url)) {
        // 将 http://localhost:3000/uploads/videos/... 转换为 /uploads/videos/...
        // 这样会通过前端代理访问
        const proxyPath = url.replace('http://localhost:3000', '');
        return proxyPath;
      }
      return url;
    },
    
    handleModalOverlayClick(e) {
      if (e.target.classList.contains('modal')) {
        this.hideCourseModal()
        this.hideEditCourseModal()
        this.hideChapterModal()
      }
    },
    showLoginModal() {
      // Handle login modal
    },
    showRegisterModal() {
      // Handle register modal
    },
    async handleLogout() {
      try {
        await apiService.logout()
      } catch (error) {
        console.error('注销失败:', error)
      } finally {
        this.currentUser = null
        this.$router.push('/')
      }
    },
    triggerFileInput() {
      this.$refs.videoFileInput.click();
    },
    
    // 获取视频时长
    async getVideoDuration(videoUrl) {
      return new Promise((resolve) => {
        // 创建临时video元素来获取视频时长
        const video = document.createElement('video');
        video.preload = 'metadata';
        video.src = videoUrl;
        
        video.onloadedmetadata = () => {
          // 获取视频时长（秒转分钟）
          const durationInMinutes = Math.ceil(video.duration / 60);
          this.currentChapter.duration = durationInMinutes;
          video.remove(); // 清理临时元素
          resolve(durationInMinutes);
        };
        
        video.onerror = () => {
          console.error('获取视频时长失败');
          video.remove(); // 清理临时元素
          resolve(0);
        };
      });
    },
    
    async handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 验证文件类型
      if (!file.type.startsWith('video/')) {
        await this.$alert('请选择视频文件', {
          title: '文件类型错误',
          variant: 'warning'
        });
        return;
      }
      
      // 验证文件大小（限制为100MB）
      if (file.size > 100 * 1024 * 1024) {
        await this.$alert('文件大小不能超过100MB', {
          title: '文件过大',
          variant: 'warning'
        });
        return;
      }
      
      try {
        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('video', file);
        
        // 显示上传进度
        this.uploadProgress = 0;
        
        // 调用 API 上传文件
        const response = await apiService.uploadVideo(formData);
        
        // 上传成功后，将返回的 URL 设置为当前章节的视频链接
        // 修复：正确处理后端返回的数据结构
        if (response && response.data && response.data.url) {
          // 使用Vue 3的响应式更新方式
          this.currentChapter.videoUrl = response.data.url;
          
          // 自动获取视频时长
          await this.getVideoDuration(response.data.url);
          
          await this.saveChapter(); // 自动保存章节
          
          // 使用nextTick确保DOM更新完成
          this.$nextTick(() => {
            console.log('视频URL已更新:', this.currentChapter.videoUrl);
            // 强制检查视频预览区域是否显示
            this.checkVideoPreview();
          });
          
          await this.$toast('视频上传成功！', {
            title: '上传成功',
            variant: 'success'
          });
        }
      } catch (error) {
        console.error('视频上传失败:', error);
        await this.$toast('视频上传失败: ' + (error.message || '未知错误'), {
          title: '上传失败',
          variant: 'error'
        });
      } finally {
        // 重置上传进度和文件输入
        this.uploadProgress = 0;
        event.target.value = '';
      }
    },
    
    // 检查视频预览是否正确显示
    checkVideoPreview() {
      console.log('检查视频预览显示状态:');
      console.log('- currentChapter:', this.currentChapter);
      console.log('- currentChapter.videoUrl:', this.currentChapter?.videoUrl);
      console.log('- isUploadedVideo:', this.isUploadedVideo(this.currentChapter?.videoUrl));
      console.log('- getProxyVideoUrl:', this.getProxyVideoUrl(this.currentChapter?.videoUrl));
      
      // 检查视频预览元素是否存在
      this.$nextTick(() => {
        const videoPreview = document.querySelector('.video-preview');
        if (videoPreview) {
          console.log('- video-preview元素存在:', videoPreview.style.display);
        } else {
          console.log('- video-preview元素不存在');
        }
      });
    },
    
    initializePlyrPlayer() {
      // 确保DOM已经更新
      this.$nextTick(() => {
        if (this.$refs.videoPlayer && !this.plyrPlayer) {
          // 销毁任何现有的播放器实例
          if (this.plyrPlayer) {
            this.plyrPlayer.destroy()
          }
          
          // 初始化Plyr播放器
          this.plyrPlayer = new Plyr(this.$refs.videoPlayer, {
            controls: [
              'play-large', // The large play button in the center
              'restart', // Restart playback
              'rewind', // Rewind by the seek time (default 10 seconds)
              'play', // Play/pause playback
              'fast-forward', // Fast forward by the seek time (default 10 seconds)
              'progress', // The progress bar and scrubber for playback and buffering
              'current-time', // The current time of playback
              'duration', // The full duration of the media
              'mute', // Toggle mute
              'volume', // Volume control
              'captions', // Toggle captions
              'settings', // Settings menu
              'pip', // Picture-in-picture (Chrome only)
              'airplay', // Airplay (Safari only)
              'download', // Show a download button with a link to either the current source or a custom URL you specify in your options
              'fullscreen' // Toggle fullscreen
            ],
            i18n: {
              restart: '重新播放',
              rewind: '快退 {seektime} 秒',
              play: '播放',
              pause: '暂停',
              fastForward: '快进 {seektime} 秒',
              seek: 'Seek',
              seekLabel: '{currentTime} of {duration}',
              played: 'Played',
              buffered: 'Buffered',
              currentTime: '当前时间',
              duration: '时长',
              volume: '音量',
              mute: '静音',
              unmute: '取消静音',
              enableCaptions: '开启字幕',
              disableCaptions: '关闭字幕',
              download: '下载',
              enterFullscreen: '全屏',
              exitFullscreen: '退出全屏',
              frameTitle: 'Player for {title}',
              captions: '字幕',
              settings: '设置',
              pip: '画中画',
              menuBack: '返回',
              speed: '速度',
              normal: '正常',
              quality: '质量',
              loop: '循环'
            }
          })
        }
      })
    },
    // 无需要保留的方法
  },
  beforeUnmount() {
    // 组件销毁前的清理工作
  }
}
</script>

<style scoped>
/* Import the CSS styles */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');

.video-course-app {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8fafc;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* Sidebar Styles */
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.sidebar-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.sidebar-actions {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.course-list {
  flex: 1;
  padding: 1rem;
}

.course-item {
  padding: 1rem;
  margin-bottom: 0.5rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-item:hover {
  background: #f8fafc;
  border-color: #e2e8f0;
}

.course-item.active {
  background: #eff6ff;
  border-color: #3b82f6;
}

.course-info {
  flex: 1;
  min-width: 0;
}

.course-actions {
  display: flex;
  gap: 0.25rem;
  opacity: 0;
  transition: opacity 0.2s ease;
  margin-left: 0.5rem;
}

.course-item:hover .course-actions {
  opacity: 1;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border: none;
  background: #f1f5f9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #64748b;
  font-size: 9px;
}

.action-btn:hover {
  background: #e2e8f0;
  color: #1e293b;
}

.course-name {
  font-size: 12px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 0.25rem;
}

.course-chapters {
  font-size: 11px;
  color: #64748b;
}

/* 创建新课程卡片样式 */
.add-course {
  border: 2px dashed #e2e8f0 !important;
  background: #f8fafc !important;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 80px;
}

.add-course:hover {
  border-color: #3b82f6 !important;
  background: #eff6ff !important;
}

.add-course-content {
  text-align: center;
  color: #64748b;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.add-course-content i {
  font-size: 18px;
  color: #3b82f6;
}

.add-course-content span {
  font-size: 12px;
  font-weight: 500;
}

/* Content Area */
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-header {
  padding: 1rem 2rem;
  background: white;
  border-bottom: 1px solid #e2e8f0;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-item {
  text-decoration: none;
  color: #64748b;
}

.breadcrumb-item:hover {
  color: #3b82f6;
}

/* Welcome Screen */
.welcome-screen {
  flex: 1;
  display: flex;
  align-items: baseline;
  justify-content: center;
  min-height: 400px;
  text-align: center;
  padding: 2rem;
}

.welcome-content i {
  font-size: 64px;
  color: #cbd5e1;
  margin-bottom: 1rem;
}

.welcome-content h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.welcome-content p {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 2rem;
}

/* Chapter View */
.chapter-view {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.chapter-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.chapter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.chapter-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
}

.chapter-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #3b82f6;
}

.video-chapter-card {
  position: relative;
}

.video-thumbnail {
  position: relative;
  height: 160px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.thumbnail-placeholder {
  color: white;
  font-size: 48px;
  opacity: 0.7;
}

.video-duration {
  position: absolute;
  bottom: 0.5rem;
  right: 0.5rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
}

.video-number {
  position: absolute;
  top: 0.5rem;
  left: 0.5rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
}

.chapter-content {
  padding: 1rem;
}

.chapter-content h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.chapter-meta {
  font-size: 11px;
  color: #64748b;
}

.chapter-actions {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.video-chapter-card:hover .chapter-actions {
  opacity: 1;
}

.action-btn {
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 4px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.action-btn:hover {
  background: rgba(239, 68, 68, 0.8);
}

.add-chapter {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #cbd5e1;
  background: #f8fafc;
  min-height: 200px;
}

.add-chapter-content {
  text-align: center;
  color: #64748b;
}

.add-chapter-content i {
  font-size: 24px;
  margin-bottom: 0.5rem;
}

/* Video Editor */
.video-editor-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-header {
  padding: 1rem;
  background: white;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-input {
  font-size: 16px;
  font-weight: 600;
  border: none;
  outline: none;
  background: transparent;
  color: #1e293b;
  width: 100%;
}

.editor-actions {
  display: flex;
  gap: 0.5rem;
}

.video-form {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
  background: #f8fafc;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 12px;
  font-weight: 500;
  color: #374151;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 12px;
  transition: border-color 0.2s ease;
  background: white;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
}

.form-select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  background-color: white;
  font-size: 0.875rem;
  line-height: 1.25rem;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.video-preview {
  margin-top: 2rem;
}

.video-preview h4 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 1rem;
}

.video-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 aspect ratio */
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 原生视频播放器样式 */
.native-video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  outline: none;
}

/* Button Styles */
.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid transparent;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.btn-ghost {
  background: transparent;
  color: #64748b;
  border-color: #e2e8f0;
}

.btn-ghost:hover {
  background: #f8fafc;
  color: #1e293b;
}

.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 11px;
}

/* 文件上传样式 */
.file-upload-area {
  border: 2px dashed #cbd5e1;
  border-radius: 6px;
  padding: 1rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #f8fafc;
}

.file-upload-area:hover {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.file-input {
  display: none;
}

.file-upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  color: #64748b;
}

.file-upload-placeholder i {
  font-size: 24px;
  color: #94a3b8;
}

.file-upload-placeholder span {
  font-size: 12px;
}

.upload-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background-color: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #3b82f6;
  transition: width 0.3s ease;
}

/* Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

.modal-content {
  background: white;
  border-radius: 12px;
  max-width: 500px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.modal-close {
  background: #f1f5f9;
  border: none;
  border-radius: 6px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #64748b;
  transition: all 0.2s ease;
}

.modal-close:hover {
  background: #e2e8f0;
  color: #1e293b;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  padding: 1.5rem;
  border-top: 1px solid #e2e8f0;
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

/* Responsive Design */
@media (max-width: 768px) {
  .main-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    max-height: 200px;
  }
  
  .chapter-grid {
    grid-template-columns: 1fr;
  }
  
  .video-form {
    padding: 1rem;
  }
  
  .editor-header {
    padding: 1rem;
  }
}
</style>